package com.jp.refreshlocalcacheclient.net.netty.request;

import com.jp.refreshlocalcacheclient.net.netty.NettyRequest;
import com.jp.refreshlocalcacheclient.net.netty.message.IMessageIds;
import com.jp.refreshlocalcacheclient.net.netty.message.RequestMessage;
import com.jp.refreshlocalcacheclient.net.netty.response.RefresResultResponseMsg;
import com.jp.refreshlocalcacheclient.process.HandleRefreshProcess;
import com.jp.refreshlocalcacheclient.utils.ApplicationContextUtil;
import io.netty.channel.ChannelHandlerContext;
import org.apache.commons.lang3.exception.ExceptionUtils;


/**
 * @Author: jipeng
 * @Description: 客户端的刷新结果通知
 * @Date: Created in 2020/5/14 18:15
 */
@NettyRequest( msgId = IMessageIds.REFRESH_NOTICE)
public class RefresRequest extends RequestMessage {


    private HandleRefreshProcess handleRefreshProcess;

    @Override
    protected void process(ChannelHandlerContext ctx) {
        String content = getContent();
        logger.info("received server content：{}", content);

        //根据content 找出需要刷新的方法，执行调用
        if(handleRefreshProcess == null){
            handleRefreshProcess = ApplicationContextUtil.getBean(HandleRefreshProcess.class);
        }

        String result ;
        try {
            //执行刷新
            result = handleRefreshProcess.handleRefresh(content) ? content + " refresh  suceess" : content + " refresh error，no method";
        }catch (Exception e){
            logger.error("refresh {} cache exception，error => {}",content, ExceptionUtils.getStackTrace(e));
            result = content +  " refresh error，" + e.getMessage();
        }

        //返回给服务器，告知执行结果
        new RefresResultResponseMsg(result).sendTo(ctx);
    }
}
